<?php

namespace app\services;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use support\Cache;

class EmailService
{
    const SCENE_REGISTER = 'register';
    const SCENE_LOGIN = 'login';

    const VALIDATE_EMAIL = 'validate_email';
    const CHANGE_EMAIL = 'change_email';

    const SCENE_FORGET_PASSWORD = 'forget_password';

    const SCENE_BIND_EMAIL = 'bind_email';

    public static function send($email, $scene)
    {
        $code = mt_rand(100000, 999999);

        $mail = new PHPMailer(true);

        try {
            $config = ConfigService::getByGroup('email');

            $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
            $mail->isSMTP();                                            //Send using SMTP
            $mail->Host       = $config['smtp_host'];                     //Set the SMTP server to send through
            $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
            $mail->Username   = $config['email_address'];                     //SMTP username
            $mail->Password   = $config['email_password'];                               //SMTP password
            $mail->SMTPSecure = $config['email_encrypt'];            //Enable implicit TLS encryption
            $mail->Port       = $config['email_encrypt'] == PHPMailer::ENCRYPTION_SMTPS ? 465 : 587;

            //Recipients
            $mail->setFrom($config['email_address'], $config['email_sender']);
            $mail->addAddress($email);     //Add a recipient

            $mail->isHTML(true);                                  //Set email format to HTML
            $mail->Subject = $config['email_subject'];
            $mail->Body    = str_replace('#####', $code, $config['email_body']);

            $mail->send();

            Cache::set('email-' . $scene . '-' . md5($email), $code, 30 * 60);

        } catch (\Exception $e) {
            echo $e->getMessage() . $e->getTraceAsString();
        }

    }

    public static function checkCode($email, $scene, $code)
    {
        if (Cache::get('email-' . $scene . '-' . md5($email)) == $code) {
            Cache::delete('email-' . $scene . '-' . md5($email));
            return;
        }

        throw new \Exception('不正确的验证码');
    }
}